package model

import (
    "time"
)

type Staff struct {
    base            `json:"-" field:"-"`
    StaffId  int    `field:"staff_id"`
    Username string `field:"username"`
    Password string `field:"password"`
    Phone    string `field:"phone"`
    Created  int    `field:"created"`
}

func NewStaff() *Staff {
    m := new(Staff)
    m.init("staff")
    return m
}

func (this *Staff) Add() error {
    this.Created = int(time.Now().Unix())
    if id, err := this.DB.Insert(this); err != nil {
        return err
    } else {
        this.StaffId = id
    }
    return nil
}

func (this *Staff) GetAll() (list []*Staff, err error) {
    res, err := this.DB.FindAll()
    if err != nil || res == nil {
        return
    }
    res.Scan(&list)
    return
}

func (this *Staff) GetByName(username string) (*Staff, error) {
    cond := this.DB.NewCondition()
    cond.SetFilter("username", username)
    res, err := this.DB.SetCondition(cond).FindOne()
    if err != nil {
        return nil, err
    }
    if res == nil {
        return nil, nil
    }
    var m Staff
    res.Scan(&m)
    return &m, nil
}

func (this *Staff) Update(updatePassword bool) error {
    this.Created = int(time.Now().Unix())
    var field string
    if updatePassword {
        field = "staff_id, created"
    } else {
        field = "staff_id, created, password"
    }
    cond := this.DB.NewCondition()
    cond.SetFilter("staff_id", this.StaffId)
    if id, err := this.DB.SetCondition(cond).SetNotUseField(field).Update(this); err != nil {
        return err
    } else {
        this.StaffId = id
    }
    return nil
}

func (this *Staff) GetById(staffId int64) error {
    cond := this.DB.NewCondition()
    cond.SetFilter("staff_id", staffId)
    res, err := this.DB.SetCondition(cond).FindOne()
    if err != nil {
        return err
    }
    if res == nil {
        return nil
    }
    res.Scan(this)
    return nil
}
